package com.loyal.helper;

import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;

import com.google.android.material.textfield.TextInputLayout;

public class UIHelper {
    private static final Resources resources = Resources.getSystem();

    /**
     * private控制不应该被实例化
     */
    private UIHelper() {
        throw new UnsupportedOperationException("不支持被实例化");
    }

    @NonNull
    public static String getInputText(@Nullable TextInputLayout inputLayout) {
        if (null == inputLayout)
            return "";
        return getInputText(inputLayout.getEditText());
    }

    @NonNull
    public static String getInputText(@Nullable EditText editText) {
        if (null == editText)
            return "";
        Editable editable = editText.getText();
        return TextUtils.isEmpty(editable) ? "" : editable.toString().trim();
    }

    public static void toastShort(@NonNull Context context, @StringRes int resId) {
        toastShort(context, resources.getText(resId));
    }

    public static void toastShort(@NonNull Context context, @NonNull CharSequence sequence) {
        showToast(context, sequence, Toast.LENGTH_SHORT);
    }

    public static void toastLong(@NonNull Context context, @StringRes int resId) {
        toastLong(context, resources.getText(resId));
    }

    public static void toastLong(@NonNull Context context, @NonNull CharSequence sequence) {
        showToast(context, sequence, Toast.LENGTH_LONG);
    }

    private static void showToast(Context context, CharSequence sequence, int duration) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Toast.makeText(context, sequence, duration).show();
        } else {
            showAsSingle(context, sequence, duration);
        }
    }

    private static Toast mToast = null;//全局唯一的Toast

    public static void errorToast(Context context, @NonNull CharSequence sequence, Throwable e) {
        String error = null == e ? "" : ErrorHelper.getMessage(e);
        String err = TextUtils.isEmpty(error) ? "" : "\n" + error;
        showAsSingle(context, sequence + err, Toast.LENGTH_LONG);
    }

    /**
     * 自定义显示Toast时间-内存泄露
     *
     * @param duration 单位:毫秒
     */
    public static void showAsSingle(Context context, CharSequence message, int duration) {
        if (null == mToast) {
            mToast = Toast.makeText(context, message, duration);
        } else {
            mToast.setText(message);
            mToast.setDuration(duration);
        }
        mToast.show();
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，
     * 来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     * {@link android.app.Activity#dispatchTouchEvent(MotionEvent)}
     * 点击空白处，隐藏键盘
     */
    public static boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] location = {0, 0};
            v.getLocationInWindow(location);
            int left = location[0],
                    top = location[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            // 点击EditText的事件，忽略它。
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    public static void hideKeyBoard(@Nullable View view) {
        if (null == view)
            return;
        hideKeyBoard(view.getContext(), view.getWindowToken());
    }

    public static void hideKeyBoard(@Nullable Context context, @Nullable IBinder token) {
        if (null == context || null == token)
            return;
        InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (im != null)
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 全屏下不显示导航栏
     */
    public static void fullScreenImmersive(Window window) {
        if (null == window) return;
        View view = window.getDecorView();
        if (null == view) return;
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_FULLSCREEN;

        view.setSystemUiVisibility(uiOptions);
    }
}
